﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using TxtSearch.Model;

namespace TxtSearch.Webapi.ExtendModule
{
    /// <summary>
    /// 消息实时通信
    /// </summary>
    public class HubMessageServer : Hub
    {
        public string Key { get; set; }
        private readonly ILogger<HubMessageServer> logger;
        public HubMessageServer(ILogger<HubMessageServer> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 用于客户端调用
        /// </summary>
        /// <param name="who"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task ReceiveMessage(string who, HubMessageModel message)
        {
            logger?.LogInformation($"{who}:{JsonConvert.SerializeObject(message)}");
            switch (message.MessageType)
            {
                default:
                    await SendMessage(message);
                    break;
            }
            await Task.CompletedTask;
        }
        public async Task SendMessage(HubMessageModel message)
        {
            try
            {
                if (Clients == null)
                {
                    logger.LogError("指令没有接受者");
                }
                else
                {
                    await Clients.All.SendAsync("ReceiveMessage", message);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{Key}发送消息错误:{JsonConvert.SerializeObject(message)}");
            }
        }
        public override Task OnConnectedAsync()
        {
            logger?.LogInformation("连接成功");
            return base.OnConnectedAsync();
        }
        public override Task OnDisconnectedAsync(Exception exception)
        {
            logger?.LogInformation("连接中断");
            return base.OnDisconnectedAsync(exception);
        }
    }
}
